﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Model.ModelsExt;
using AntUnion.FrameWork.Util;
using AntUnion.FrameWork.Web.Common;
using AntUnion.FrameWork.Web.Extend;
using AntUnion.FrameWork.Web.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml.Drawing.Chart;
using RM.Common.DotNetEamil;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using TencentCloud.Bm.V20180423.Models;
using TencentCloud.Tdmq.V20200217.Models;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace AntUnion.FrameWork.Web.Controllers
{
    public class LoginController : SystemMaintenanceController
    {
        public int expires = 60;
        public int cacheExpires = 15;
        public CrmService crmService = new CrmService();
        public LogService logService = new LogService();
        public RoleService roleService = new RoleService();
        public AssetsServer assetsServer = new AssetsServer();
        public MeunService meunService = new MeunService();
        public Mt5Service mt5Service = new Mt5Service();
        public PublicService publicService = new PublicService();
        private readonly SmtpSettings _emailSender;

        public LoginController(SmtpSettings emailSender)
        {
            _emailSender = emailSender;
        }
        #region 登录

        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Index(string language = "user-zh-CN")
        {
            string defaultLanguage = "zh-CN";
            if (language == "user-en-US")
            {
                defaultLanguage = "en-US";
            }
            List<PublicService.SystemConfigModel> systemConfigModels = publicService.GetSystemConfig();
            ViewBag.webFrontTitle = systemConfigModels.FirstOrDefault(k => k.name == "webFrontTitle" && k.language == defaultLanguage).value;
            ViewBag.sitename = systemConfigModels.FirstOrDefault(k => k.name == "webFrontName" && k.language == defaultLanguage).value;
            //ViewBag.userloginlogo = systemConfigModels.FirstOrDefault(k => k.name == "userloginlogo").value;
            ViewBag.logo = systemConfigModels.FirstOrDefault(k => k.name == "webFrontLogo").value;
            ViewBag.loginWarmPrompt = systemConfigModels.FirstOrDefault(k => k.name == "loginWarmPrompt" && k.language == defaultLanguage).value;
            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userPwd"></param>
        /// <param name="validCode"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Login(string email, string userPwd)
        {
            Result res = new Result();
            try
            {
                if (string.IsNullOrEmpty(email))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.emailNull;
                    return new JsonResult(res);
                }
                if (!publicService.IsValidEmail(email))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.emailError;
                    return new JsonResult(res);
                }
                if (string.IsNullOrEmpty(userPwd))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.passwordNull;
                    return new JsonResult(res);
                }
                string encryptPwd = SecurityUtil.EncryptPwd(userPwd);
                string ip = HttpContext.Connection.RemoteIpAddress.ToString();
                string ipAddress = "";
                if (ip != "::1")
                {
                    string[] ips = ip.Split('.');
                    if (ips.Length == 4)
                    {
                        try
                        {
                            IPModel iPModel = HttpUtil.HttpGet($"http://whois.pconline.com.cn/ipJson.jsp?ip={ip}&json=true").ToObject<IPModel>();
                            ipAddress = iPModel.addr;
                        }
                        catch
                        {
                            ipAddress = "";
                        }
                    }
                }
                CrmUser crmUser = crmService.GetCrmUser(email, encryptPwd, ip);

                if (crmUser != null)
                {
                    if (crmUser.State == 1)
                    {
                        TbRole role = roleService.GetRole(crmUser.Id, UserType.CrmUser);
                        CrmUserModel crmUserModel = new CrmUserModel
                        {
                            Id = crmUser.Id,
                            Name = crmUser.Name,
                            LoginName = crmUser.LoginName,
                            RoleId = role.Id,
                            State = crmUser.State,
                            SessionId = HttpContext.Session.Id
                        };
                        HttpContext.Session.Set("CrmUser", ByteConvertUtil.Serialize(crmUserModel));
                        HttpContext.Response.Cookies.Append("CrmUser", email + "|" + userPwd, new CookieOptions
                        {
                            Expires = DateTime.Now.AddHours(expires)
                        });
                        logService.AddLoginLogs(HttpContext, crmUser.LoginName, crmUser.Id, 1, "loginSucceeded", ip, ipAddress, 1);
                        using (mtContext _context = new mtContext())
                        {
                            _context.SaveChanges();
                        }
                        res.Code = 0;
                        res.Msg = LanguageConfig.loginSuccess;
                    }
                    else
                    {
                        logService.AddLoginLogs(HttpContext, crmUser.LoginName, crmUser.Id, 0, "loginManagementSystemFailed", ip, ipAddress, 1);
                        res.Code = 1;
                        res.Msg = LanguageConfig.disabledAccount;
                    }
                }
                else
                {
                    logService.AddLoginLogs(HttpContext, email, 0, 0, "loginManagementSystemFailed", ip, ipAddress, 1);
                    res.Code = 1;
                    res.Msg = LanguageConfig.loginFaile;
                }
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
            }
            return new JsonResult(res);
        }

        /// <summary>
        /// 需要登录页面
        /// </summary>
        /// <returns></returns>
        public IActionResult NeedLogin()
        {
            return View();
        }

        #endregion

        #region 注册

        /// <summary>
        /// 注册页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Register(string language = "user-zh-CN")
        {
            string defaultLanguage = "zh-CN";
            if (language == "user-en-US")
            {
                defaultLanguage = "en-US";
            }
            List<PublicService.SystemConfigModel> systemConfigModels = publicService.GetSystemConfig();
            ViewBag.webFrontTitle = systemConfigModels.FirstOrDefault(k => k.name == "webFrontTitle" && k.language == defaultLanguage).value;
            ViewBag.sitename = systemConfigModels.FirstOrDefault(k => k.name == "webFrontName" && k.language == defaultLanguage).value;
            //ViewBag.userloginlogo = systemConfigModels.FirstOrDefault(k => k.name == "userloginlogo").value;
            ViewBag.logo = systemConfigModels.FirstOrDefault(k => k.name == "webFrontLogo").value;
            ViewBag.registrationWarmPrompt = systemConfigModels.FirstOrDefault(k => k.name == "registrationWarmPrompt" && k.language == defaultLanguage).value;
            return View();
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userPwd"></param>
        /// <param name="validCode"></param>
        /// <param name="group"></param>
        /// <param name="up"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Register(string email, string userPwd, string validCode, string p)
        {
            Result res = new Result();
            try
            {
                if (string.IsNullOrEmpty(email))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.emailNull;
                    return new JsonResult(res);
                }
                if (!publicService.IsValidEmail(email))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.emailError;
                    return new JsonResult(res);
                }
                if (string.IsNullOrEmpty(validCode))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.validCodeNull;
                    return new JsonResult(res);
                }
                if (string.IsNullOrEmpty(userPwd))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.passwordNull;
                    return new JsonResult(res);
                }
                if (!publicService.IsValidPassword(userPwd))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.passwordError;
                    return new JsonResult(res);
                }

                string code = publicService.GetCache<string>(email);
                if (code != null)
                {
                    if (code != validCode)
                    {
                        res.Code = 1;
                        res.Msg = LanguageConfig.validCodeError;
                        return new JsonResult(res);
                    }
                    CrmUser crmUser = crmService.GetCrmUser(email);
                    //用户不存在，可以注册
                    if (crmUser == null)
                    {
                        string encryptPwd = SecurityUtil.EncryptPwd(userPwd);
                        uint group = 0;
                        int up = 0;
                        if (!string.IsNullOrEmpty(p))
                        {
                            string str = SecurityUtil.Decrypt(p);
                            NameValueCollection queryParams = HttpUtility.ParseQueryString(str);
                            try
                            {
                                group = uint.Parse(queryParams["group"]);
                            }
                            catch (Exception)
                            {
                                group = 0;
                            }

                            try
                            {
                                up = int.Parse(queryParams["up"]);
                            }
                            catch (Exception)
                            {
                                up = 0;
                            }
                        }
                        int count = crmService.AddCrmUser(email, encryptPwd, group, up, Source.User);
                        res.Code = 0;
                        res.Msg = LanguageConfig.registerSuccess;
                        return new JsonResult(res);
                    }
                    else
                    {
                        res.Code = 1;
                        res.Msg = LanguageConfig.hasAccount;
                        return new JsonResult(res);
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.validCodeError;
                    return new JsonResult(res);
                }
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
                return new JsonResult(res);
            }
        }

        #endregion

        #region 忘记密码

        /// <summary>
        /// 忘记密码
        /// </summary>
        /// <returns></returns>
        public IActionResult Forget(string language = "user-zh-CN")
        {
            string defaultLanguage = "zh-CN";
            if (language == "user-en-US")
            {
                defaultLanguage = "en-US";
            }
            List<PublicService.SystemConfigModel> systemConfigModels = publicService.GetSystemConfig();
            ViewBag.webFrontTitle = systemConfigModels.FirstOrDefault(k => k.name == "webFrontTitle" && k.language == defaultLanguage).value;
            ViewBag.sitename = systemConfigModels.FirstOrDefault(k => k.name == "webFrontName" && k.language == defaultLanguage).value;
            //ViewBag.userloginlogo = systemConfigModels.FirstOrDefault(k => k.name == "userloginlogo").value;
            ViewBag.logo = systemConfigModels.FirstOrDefault(k => k.name == "webFrontLogo").value;
            ViewBag.passwordWarmPrompt = systemConfigModels.FirstOrDefault(k => k.name == "passwordWarmPrompt" && k.language == defaultLanguage).value;
            return View();
        }

        /// <summary>
        /// 忘记密码
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userPwd"></param>
        /// <param name="validCode"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Forget(string email, string newPwd, string confirmPwd, string validCode)
        {
            Result res = new Result();
            try
            {
                if (string.IsNullOrEmpty(email))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.emailNull;
                    return new JsonResult(res);
                }
                if (!publicService.IsValidEmail(email))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.emailError;
                    return new JsonResult(res);
                }
                if (string.IsNullOrEmpty(validCode))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.validCodeNull;
                    return new JsonResult(res);
                }
                if (string.IsNullOrEmpty(newPwd))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.passwordNull;
                    return new JsonResult(res);
                }
                if (!publicService.IsValidPassword(newPwd))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.passwordError;
                    return new JsonResult(res);
                }
                if (string.IsNullOrEmpty(confirmPwd))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.passwordNull;
                    return new JsonResult(res);
                }
                if (!publicService.IsValidPassword(confirmPwd))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.passwordError;
                    return new JsonResult(res);
                }
                if (newPwd != confirmPwd)
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.passwordDifferent;
                    return new JsonResult(res);
                }
                //读取Session
                string code = publicService.GetCache<string>(email);
                if (code != null)
                {
                    if (code != validCode)
                    {
                        res.Code = 1;
                        res.Msg = LanguageConfig.validCodeError;
                        return new JsonResult(res);
                    }
                    CrmUser crmUser = crmService.GetCrmUser(email);
                    if (crmUser != null)
                    {
                        string encryptPwd = SecurityUtil.EncryptPwd(newPwd);
                        //用户不存在，可以注册
                        int count = crmService.UpdateCrmPassword(crmUser.Id, encryptPwd);
                        res.Code = 0;
                        res.Msg = LanguageConfig.forgetSuccess;
                        return new JsonResult(res);
                    }
                    else
                    {
                        res.Code = 1;
                        res.Msg = LanguageConfig.accountNull;
                        return new JsonResult(res);
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.validCodeError;
                    return new JsonResult(res);
                }
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
                return new JsonResult(res);
            }
        }

        #endregion

        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> SendValidateCode(string email, string type)
        {
            Result res = new Result();
            try
            {
                if (string.IsNullOrEmpty(email))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.emailNull;
                    return new JsonResult(res);
                }
                if (!publicService.IsValidEmail(email))
                {
                    res.Code = 1;
                    res.Msg = LanguageConfig.emailError;
                    return new JsonResult(res);
                }
                string code = ValidateCode.CreateValidateCode(6);
                string title = "";
                if (type == "register")
                {
                    title = "账号注册";
                    CrmUser crmUser = crmService.GetCrmUser(email);
                    if (crmUser != null)
                    {
                        res.Code = 1;
                        res.Msg = LanguageConfig.hasAccount;
                        return new JsonResult(res);
                    }
                    //发送邮件
                    await RM.Common.DotNetEamil.NetEmailClient.SendMailByConfig(email, title, RM.Common.DotNetEamil.NetEmailClient.GetCode(code, cacheExpires), "");
                }
                else if (type == "forget")
                {
                    title = "忘记密码";
                    CrmUser crmUser = crmService.GetCrmUser(email);
                    if (crmUser == null)
                    {
                        res.Code = 1;
                        res.Msg = LanguageConfig.accountNull;
                        return new JsonResult(res);
                    }
                    //发送邮件
                    await RM.Common.DotNetEamil.NetEmailClient.SendMailByConfig(email, title, RM.Common.DotNetEamil.NetEmailClient.ForgetPasswordCode(code, cacheExpires), "");
                }
                else if (type == "updatePhone")
                {
                    title = "修改手机";
                    //发送邮件
                    await RM.Common.DotNetEamil.NetEmailClient.SendMailByConfig(email, title, RM.Common.DotNetEamil.NetEmailClient.UpdateTelCode(code, cacheExpires), "");
                }
                else if (type == "updateEmail")
                {
                    title = "修改邮箱";
                    //发送邮件
                    await RM.Common.DotNetEamil.NetEmailClient.SendMailByConfig(email, title, RM.Common.DotNetEamil.NetEmailClient.UpdateEmailCode(code, cacheExpires), "");
                }
                else if (type == "updatePassword")
                {
                    title = "修改密码";
                    //发送邮件
                    await RM.Common.DotNetEamil.NetEmailClient.SendMailByConfig(email, title, RM.Common.DotNetEamil.NetEmailClient.UpdatePasswordCode(code, cacheExpires), "");
                }
                else if (type == "updateTradePassword")
                {
                    title = "修改交易密码";
                    //发送邮件
                    await RM.Common.DotNetEamil.NetEmailClient.SendMailByConfig(email, title, RM.Common.DotNetEamil.NetEmailClient.GetCode(code, cacheExpires), "");
                }
                //发送邮件
                //await RM.Common.DotNetEamil.NetEmailClient.SendMailByConfig(_emailSender, email, title, RM.Common.DotNetEamil.NetEmailClient.GetCode(code, cacheExpires), "");
                //发送成功，存入Session
                res.Data = publicService.SetCache(email, code, TimeSpan.FromMinutes(cacheExpires));
                res.Code = 0;
                res.Msg = LanguageConfig.sendSuccess;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 用户协议
        /// </summary>
        /// <returns></returns>
        public IActionResult UserAgreement(string language = "user-zh-CN")
        {
            string defaultLanguage = "zh-CN";
            if (language == "user-en-US")
            {
                defaultLanguage = "en-US";
            }
            List<PublicService.SystemConfigModel> systemConfigModels = publicService.GetSystemConfig();
            ViewBag.webFrontTitle = systemConfigModels.FirstOrDefault(k => k.name == "webFrontTitle" && k.language == defaultLanguage).value;
            ViewBag.sitename = systemConfigModels.FirstOrDefault(k => k.name == "webFrontName" && k.language == defaultLanguage).value;
            ViewBag.logo = systemConfigModels.FirstOrDefault(k => k.name == "webFrontLogo").value;
            ViewBag.userAgreement = systemConfigModels.FirstOrDefault(k => k.name == "userAgreement" && k.language == defaultLanguage).value;
            return View();
        }

        /// <summary>
        /// 隐私条款
        /// </summary>
        /// <returns></returns>
        public IActionResult PrivacyClause(string language = "user-zh-CN")
        {
            string defaultLanguage = "zh-CN";
            if (language == "user-en-US")
            {
                defaultLanguage = "en-US";
            }
            List<PublicService.SystemConfigModel> systemConfigModels = publicService.GetSystemConfig();
            ViewBag.webFrontTitle = systemConfigModels.FirstOrDefault(k => k.name == "webFrontTitle" && k.language == defaultLanguage).value;
            ViewBag.sitename = systemConfigModels.FirstOrDefault(k => k.name == "webFrontName" && k.language == defaultLanguage).value;
            ViewBag.logo = systemConfigModels.FirstOrDefault(k => k.name == "webFrontLogo").value;
            ViewBag.privacyClause = systemConfigModels.FirstOrDefault(k => k.name == "privacyClause" && k.language == defaultLanguage).value;
            return View();
        }
    }
}
